package com.ewancle;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        // WebDriver driver = new ChromeDriver();

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        //options.setD
        WebDriver driver = new ChromeDriver(options);
        driver.get("https://www.selenium.dev/selenium/web/web-form.html");

        /*Chrome: https://chromedriver.chromium.org/downloads
        Edge: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
        Firefox: https://github.com/mozilla/geckodriver/releases*/

        // https://www.baeldung.com/java-selenium-webdriver-path-error
        System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe");
        System.setProperty("webdriver.gecko.driver", "src/test/resources/geckodriver.exe");
        System.setProperty("webdriver.edge.driver", "src/test/resources/msedgedriver.exe");


        String path = System.getProperty("user.dir");   // return project folder path
        String driverpath = path + "\\driverfolder\\chromedriver.exe";   // return driver folder path
        System.setProperty("webdriver.chrome.driver",driverpath );
        //System.setProperty("webdriver.chrome.driver", "src\\main\\resources\\chromedriver.exe"); // "[folder]\\chromedriver.exe"

        String cookie="你的cookie";
        try {
            Document document = Jsoup.connect("https://www.4399.com")
                    .cookies(convertCookie("cookie")).get();
            document.body().text();

/*
            // 目标网站的登录URL
            String loginUrl = "http://example.com/login";
            // 使用Jsoup连接器构建请求
            Connection connection = Jsoup.connect(loginUrl);
            // 配置请求（例如表单数据）
            connection.data("username", "your_username");
            connection.data("password", "your_password");
            // 发送POST请求登录
            Connection.Response response = connection.method(Connection.Method.POST).execute();
            // 获取并打印Cookies
            Map<String, String> cookies = response.cookies();
            for (Map.Entry<String, String> entry : cookies.entrySet()) {

                System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
                // 这里可以将Cookie保存起来，例如写入文件或数据库，以便后续请求使用
            }*/

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        System.out.println( "Hello World!" );
    }


    // 打印cookie： javascript:document.write(document.cookie)
    public static HashMap<String, String> convertCookie(String cookie) {
		HashMap<String, String> cookiesMap = new HashMap<String, String>();
		String[] items = cookie.trim().split(";");
		for (String item:items) cookiesMap.put(item.split("=")[0], item.split("=")[1]);
		return cookiesMap;
	}

    /**
     * 使用参考：https://developer.aliyun.com/article/1294487
     * @param url
     * @param cookie
     * @throws IOException
     */
    public static void doGet(String url ,String cookie) throws IOException {

      url = "https://www.baidu.com/";
      cookie = "BIDUPSID=56C4FFBF72723876ACBD5B2EA2C75AD8; PSTM=1669362017; BD_UPN=12314753; BAIDUID=F4A7FCF34D70EE033317D31778290FE0:FG=1; ZFY=bMkQzdDwo03XIz75dDC8:AwpdCLhCOaBeWmYRxguNzHQ:C; BAIDUID_BFESS=F4A7FCF34D70EE033317D31778290FE0:FG=1; baikeVisitId=a61698de-af11-451a-8f37-7a0efc41ef7c; __bid_n=184d169de2c1b652e44207; RT=\"z=1&dm=baidu.com&si=7ao2cg4efas&ss=lb63h3q0&sl=3&tt=2hm&bcn=https://fclog.baidu.com/log/weirwood?type=perf&ld=31p&ul=18ia&hd=18ka\"; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; COOKIE_SESSION=439025_2_8_9_12_10_0_0_8_6_0_0_459518_56535_3_0_1670314644_1669853798_1670314641|9#56556_3_1669853666|2; BA_HECTOR=24a484ah0k84258h0h852gj41hovnrf1g; ab_sr=1.0.1_ODA0NTY3OGYzMmViNzMyNGQ1YWU1MzhjZDc1YjM2ZjQ0MjlkZjlhOTI2ZjZjMjk1N2NlODAzNjg5YjRlNDQxNjUzZjQ2M2JkZDYwOWQ2Y2Q1MDI4NzRhNjRkM2RjYmQxOGNiNjZhMTk0YjFhZThmMmE4ZjljN2MyMzJmOWFhOWNlMTk3MmZjNTcyNjNkN2RhYjQ3M2Y1MjNlMjViNjcyOQ==; BDRCVFR[PGnakqNNAQT]=mk3SLVN4HKm; BD_HOME=1; H_PS_PSSID=37856_36560_36920_37835_37841_37871_37765_37797_37760_37853_26350_22160_37881; delPer=0; BD_CK_SAM=1; PSINO=1; H_PS_645EC=35d9T+b4lE+jHT8VNaqK1aghA5CXp4Yf4fqDSH/hRVMSETsPPBQsOh069iA";
      //获取请求连接
      Connection con = Jsoup.connect(url);
      //请求头设置，特别是cookie设置
      con.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
      con.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36");
      con.header("Host","www.baidu.com");
      con.header("Referer","https://www.baidu.com/link?url=Su25Siv6Fi0gZJgDQoDcxse30NxOOLSSqQcNy0k6FU3&wd=&eqid=d8ed532b000af73400000003638feddc");
      con.header("Cookie", cookie);
      //解析请求结果
      Document doc = con.get();
      //获取标题
      System.out.println(doc.title());
      //输出网页
      System.out.println(doc.toString());
  }

}
